package com.yeyaomai.dksns.flowis.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

 
import org.apache.log4j.Logger;
import org.springframework.data.mongodb.core.mapreduce.MapReduceResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.yeyaomai.dksns.flowis.dao.AccessAnalysisDao;
import com.yeyaomai.dksns.flowis.dao.DetailDao;
import com.yeyaomai.dksns.flowis.domain.AccessAnalysis;
import com.yeyaomai.dksns.flowis.domain.Access_out;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.util.CollectionNames;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

/**
 * 
 * 定时从mongo取数据，访问分析模块数据后添加入MYSQL
 * 
 * @author zhaocm
 * 
 */
public class AccessAnalysisExecuto {
	
	@Resource
	private AccessAnalysisDao accessDao;
	@Resource
	private DetailDao detailDao;

	public void accessAnalysisTiming() throws ParseException {

		final Logger logger = Logger.getLogger("quartz");
		String st = VelocityToolDateUtils.getHour(-1);
		String et = VelocityToolDateUtils.getHour(0);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		MapReduceResults<Access_out> access_outs = this.groupAccess(st, et);

		if (access_outs.getCounts().getOutputCount() != 0) {

			for (Access_out access_out : access_outs) {

				AccessAnalysis access = new AccessAnalysis();
				access = access_out.getValue();
				if (access_out.get_id().length() > 255) {
					access.setAccess_url(access_out.get_id().substring(0, 255));
				} else {
					access.setAccess_url(access_out.get_id());
				}
				access.setDate(sdf.parse(VelocityToolDateUtils.getDay(0)));
				access.setUniqueVisitors(this.groupUv(st, et,
						CollectionNames.ACCESS_URL, access.getAccess_url()));
				access.setEnterNumber(this.groupEnter(st, et,
						CollectionNames.ACCESS_URL, access.getAccess_url()));
				access.setOutNumber(this.groupOut(st, et,
						CollectionNames.ACCESS_URL, access.getAccess_url()));
				access.setBounceNumber(this.groupBounce(st, et,
						CollectionNames.ACCESS_URL, access.getAccess_url()));

				accessDao.addAccessAnalysis(access);
			}
		}
		logger.info(" 受访页面统计： 统计时间：" + sd.format(new Date()) + "   记录数据："
				+ access_outs.getCounts().getOutputCount() + "条");
	}

	// 受访页面 浏览次数
	public MapReduceResults<Access_out> groupAccess(String st, String et) {

		String mapFunction = "function() { "
				+ "emit( this.access_url , {browseNumber : 1 , stoptime : this.stoptime });  }";

		String reduceFunction = "function(key,values){"
				+ "var ret = {browseNumber: 0, stoptime: 0};"
				+ "for( var i=0; i<values.length; i++){"
				+ "ret.browseNumber +=  values[i].browseNumber;"
				+ "ret.stoptime += values[i].stoptime; " + "} "
				+ "return ret;  }";
		Query query = new Query(Criteria.where("access_date").gte(st).lte(et));
		return detailDao.groupMapReduce(query, mapFunction, reduceFunction,
				Access_out.class);

	}

	// 对应页面的 UV数
	private int groupUv(String st, String et, String name, String value) {

		String mapFunction = "{ cookieId: 0}";
		String reduceFunction = "function(key,values) {values.cookieId+=1}";
		Criteria criteria = Criteria.where("cookieId").ne("null")
				.and("access_date").gte(st).lt(et).and(name).is(value);
		return detailDao.group(criteria, CollectionNames.COOKIEID, mapFunction,
				reduceFunction, FlowisStatDetailDTO.class).getKeys();
	}

	// 进入次数
	private int groupEnter(String st, String et, String name, String value) {

		Criteria criteria = Criteria.where("referer").is("").and("access_date")
				.gte(st).lt(et).and(name).is(value);
		return detailDao.findList(criteria).size();

	}

	// 离开次数
	private int groupOut(String st, String et, String name, String value) {

		Criteria criteria = Criteria.where("close").is(1).and("access_date")
				.gte(st).lt(et).and(name).is(value);
		return detailDao.findList(criteria).size();
	}

	// 跳出UV数 第一次进入该网站且只访问一个页面的独立访客
	private int groupBounce(String st, String et, String name, String value) {

		Criteria criteria = Criteria.where("close").is(1).and("referer")
				.is("").and("access_date").gte(st).lt(et).and(name).is(value);
		return detailDao.findList(criteria).size();
	}
}
